package com.example.admin.mybledemo.ota;

import java.util.ArrayList;
import java.util.List;

import cn.com.heaton.blelibrary.ble.BleLog;

/**
 * 第二阶段OTA协议实现
 * 完全按照Flutter端的逻辑实现
 */
public class Phase2Protocol {
    
    private static final String TAG = "Phase2Protocol";
    private static final int DATA_SIZE = 32; // 与Flutter端一致
    
    private List<String> otaContent;
    private int curPos = 0;
    private boolean otaing = false;
    
    public Phase2Protocol(List<String> otaContent) {
        this.otaContent = otaContent;
        this.curPos = 0;
        this.otaing = false;
    }
    
    /**
     * 开始第二阶段OTA（对应Flutter的_startOtaSecondStep）
     */
    public void startOtaSecondStep() {
        otaing = true;
        curPos = 0;
        BleLog.d(TAG, "开始ota第二步");
    }
    
    /**
     * 发送OTA开始命令（对应Flutter的_sendOtaStart）
     */
    public byte[] buildOtaStartCommand(String creditCode) {
        // 将凭证码转换为字节数组（4字节，小端序）
        byte[] creditBytes = hexStringToBytes(creditCode);
        byte[] creditBytesLE = reverseByteArray(creditBytes);
        
        // 构建命令：[0x01, 0x01] + 凭证码(4字节,小端)
        byte[] command = new byte[2 + 4];
        command[0] = 0x01;
        command[1] = 0x01;
        System.arraycopy(creditBytesLE, 0, command, 2, 4);
        
        BleLog.d(TAG, "构建OTA开始命令: " + bytesToHexString(command));
        
        // 与Flutter端保持一致：发送开始命令后设置curPos=3
        this.curPos = 3;
        this.otaing = true;
        
        return command;
    }
    
    /**
     * 发送块命令（对应Flutter的_sendBlockCmd）
     */
    public byte[] buildBlockCommand() {
        if (curPos >= otaContent.size()) {
            return null;
        }
        
        String blockStr = otaContent.get(curPos);
        if (!blockStr.startsWith("@")) {
            return null;
        }
        
        // 解析目标地址
        String addressHex = blockStr.substring(1, 9);
        int targetAddr = Integer.parseInt(addressHex, 16);
        byte[] targetAddrBytes = intToBytes(targetAddr, 4);
        byte[] targetAddrLE = reverseByteArray(targetAddrBytes);
        
        // 计算块大小
        int start = curPos + 1;
        int end = start + 1024;
        if (end > otaContent.size()) {
            end = otaContent.size();
        }
        
        int blockSize = (end - start) * 4; // 每行4字节
        byte[] targetSizeBytes = intToBytes(blockSize, 2);
        byte[] targetSizeLE = reverseByteArray(targetSizeBytes);
        
        // 获取块数据
        List<String> blockDataStr = otaContent.subList(start, end);
        List<Integer> blockDataArr = new ArrayList<>();
        for (String data : blockDataStr) {
            byte[] dataBytes = hexStringToBytes(data);
            byte[] dataBytesLE = reverseByteArray(dataBytes);
            for (byte b : dataBytesLE) {
                blockDataArr.add((int) b & 0xFF);
            }
        }
        
        // 计算FCS
        int[] blockDataInt = blockDataArr.stream().mapToInt(i -> i).toArray();
        byte[] blockFcs = FcsUtil.calculateFCS(blockDataInt);
        byte[] blockFcsLE = reverseByteArray(blockFcs);
        
        // 构建命令：[01,04,地址(4字节),大小(2字节),FCS(3字节)]
        byte[] command = new byte[2 + 4 + 2 + 3];
        command[0] = 0x01;
        command[1] = 0x04;
        System.arraycopy(targetAddrLE, 0, command, 2, 4);
        System.arraycopy(targetSizeLE, 0, command, 6, 2);
        System.arraycopy(blockFcsLE, 0, command, 8, 3);
        
        BleLog.d(TAG, "构建块命令: 地址=0x" + Integer.toHexString(targetAddr) + 
                ", 大小=" + blockSize + ", FCS=" + bytesToHexString(blockFcsLE));
        
        return command;
    }
    
    /**
     * 发送块数据（对应Flutter的_sendBlockData）
     */
    public byte[] buildBlockData() {
        if (curPos >= otaContent.size()) {
            return null;
        }
        
        String blockStr = otaContent.get(curPos);
        if (blockStr.startsWith("@")) {
            return null;
        }
        
        List<String> segData = new ArrayList<>();
        int size = DATA_SIZE;
        if (curPos + DATA_SIZE > otaContent.size()) {
            size = otaContent.size() - curPos;
        }
        
        segData = otaContent.subList(curPos, curPos + size);
        List<Byte> cmd = new ArrayList<>();
        
        for (String data : segData) {
            byte[] dataBytes = hexStringToBytes(data);
            byte[] dataBytesLE = reverseByteArray(dataBytes);
            for (byte b : dataBytesLE) {
                cmd.add(b);
            }
        }
        
        byte[] result = new byte[cmd.size()];
        for (int i = 0; i < cmd.size(); i++) {
            result[i] = cmd.get(i);
        }
        
        BleLog.d(TAG, "构建块数据: 大小=" + result.length + " 字节");
        return result;
    }
    
    /**
     * 构建结束命令（对应Flutter的_endCmd）
     */
    public byte[] buildEndCommand() {
        return new byte[]{0x01, 0x03};
    }
    
    /**
     * 移动到下一个位置（对应Flutter的curPos更新逻辑）
     */
    public void nextPosition() {
        curPos++;
    }
    
    /**
     * 移动到下一个位置（块数据专用）
     */
    public void nextPositionForBlockData(int size) {
        curPos += size;
    }
    
    /**
     * 检查是否完成（对应Flutter的_curPos >= _otaContent.length - 1）
     */
    public boolean isCompleted() {
        return curPos >= otaContent.size() - 1;
    }
    
    /**
     * 检查当前位置是否是块命令（对应Flutter的blockStr.startsWith('@')）
     */
    public boolean isBlockCommand() {
        if (curPos >= otaContent.size()) {
            return false;
        }
        return otaContent.get(curPos).startsWith("@");
    }
    
    /**
     * 获取当前进度百分比（与Flutter端完全一致）
     * Flutter: int progress = _curPos * 100 ~/ (_otaContent.length - 1);
     */
    public int getProgress() {
        if (otaContent.size() <= 1) {
            return 0;
        }
        int progress = curPos * 100 / (otaContent.size() - 1);
        return Math.min(progress, 100);
    }
    
    /**
     * 获取当前位置
     */
    public int getCurrentPosition() {
        return curPos;
    }
    
    /**
     * 获取总行数
     */
    public int getTotalLines() {
        return otaContent.size();
    }
    
    /**
     * 检查是否正在OTA中
     */
    public boolean isOtaing() {
        return otaing;
    }
    
    /**
     * 获取当前行的内容（用于调试）
     */
    public String getCurrentLine() {
        if (curPos >= otaContent.size()) {
            return "";
        }
        return otaContent.get(curPos);
    }
    
    // 工具方法
    private byte[] hexStringToBytes(String hexString) {
        hexString = hexString.replaceAll("\\s", "");
        if (hexString.length() % 2 != 0) {
            return new byte[0];
        }
        
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            bytes[i / 2] = (byte) Integer.parseInt(hexString.substring(i, i + 2), 16);
        }
        return bytes;
    }
    
    private byte[] intToBytes(int value, int length) {
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            bytes[i] = (byte) ((value >> (i * 8)) & 0xFF);
        }
        return bytes;
    }
    
    private byte[] reverseByteArray(byte[] bytes) {
        byte[] reversed = new byte[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            reversed[i] = bytes[bytes.length - 1 - i];
        }
        return reversed;
    }
    
    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b & 0xFF));
        }
        return sb.toString().trim();
    }
} 